package com.dandelion.api.controller;

import com.dandelion.common.constants.RedisSessionConstants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.rockit.core.utils.UniqueIdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * Created by Allen on 2016/2/6.
 */
@Controller
public class CaptchaController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @RequestMapping("/captcha")
    public void getCaptacha(HttpServletRequest request, HttpServletResponse response) {
        String verifyCode = UniqueIdUtils.getRandonHex(4);
        request.getSession().setAttribute(RedisSessionConstants.IMG_VERIFY_CODE_ + request.getSession().getId(), verifyCode);// TODO use redis
        try {
            BufferedImage challenge = defaultKaptcha.createImage(verifyCode);
            ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
            ImageIO.write(challenge, "JPEG", jpegOutputStream);
            byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");
            ServletOutputStream responseOutputStream = response.getOutputStream();
            responseOutputStream.write(captchaChallengeAsJpeg);
            responseOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
